<?php
namespace app\services;
use app\api\model\Type;
use app\api\model\Spec;
use app\api\model\SpecValue;
use app\api\model\Attribute;
use think\db\exception\DbException;
class TypeServices
{
    private static $typeId;
    private static $specData;
    /**
     * 添加模型信息入库
     * @param $data
     */
    public static function addType($data)
    {
        try {
            // 先将商品类型名称入库，此时能获得到主键id
            $type = Type::addType($data);
        } catch (DbException $exception) {
            abort(101,'商品类模型入库失败');
        }
        self::$typeId = $type->id;
        // 返回新增的商品模型
        return ['type_id'=>$type->id,'type_name'=>$type->type_name];
    }
    /**
     * 规格信息入库保存的逻辑
     * @param $data
     * @return \think\Collection
     * @throws \Exception\
     */
    public static function addSpec($data)
    {
        // 组装spec表所需数据
        $spec = [];
        foreach ($data['spec'] as $val) {
            $spec[] = [
                'type_id' => self::$typeId,
                'spec_name' => $val['name'],
                'sort' => $val['sort']
            ];
        }
        try {
            // 将商品类型对应的规格入库保存
            self::$specData = (new Spec())->addSpec($spec);
        } catch (DbException $exception) {
            abort(102,'商品类模型入库失败');

        }
    }
    /**
     * 规格值信息入库保存的逻辑
     * @param $data
     * @param $specData
     * @throws \Exception
     */
    public static function addSpecValue($data)
    {
        // 取出specValue的值
        foreach ($data['spec'] as $key => $val) {
            foreach ($val['value'] as $k => $v) {
                $specValue[] = [
                    'spec_value' => $v,
                    'type_id' => self::$typeId,
                    'spec_id' => self::$specData[$key]['id']
                ];
            }
        }
        try {
            // 将规格值入库保存
            (new SpecValue())->addSpecValue($specValue);
        } catch (DbException $exception) {
            abort(103,'商品规格入库失败');
        }
    }

    /**
     * 属性信息入库保存的逻辑
     * @param $data
     * @return \think\Collection
     * @throws \Exception
     */
    public static function addAttr($data)
    {
        // 组装商品属性的数组
        $attr = [];
        foreach ($data['attr'] as $key => $val) {
            $attr[] = [
                'attr_name' => $val['name'],
                'type_id' => self::$typeId,
                'attr_values' => implode(",", $val['value'])
            ];
        }
        try {
            // 将商品属性入库保存
            (new Attribute())->addAttr($attr);
        } catch (DbException $exception) {
            abort(103,'商品属性入库失败');

        }
    }



}
